<?php

namespace App\Http\Controllers;

use App\Models\Config;
use App\Models\Record;
use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    //
    public function index(Request $request)
    {
        $user = $request->user();
        if ($user->id == 1) $user->system = 1;
        if ($user->id == 2) $user->system = 1;
        return $this->response($request->user());
    }

    public function update($id,Request $request)
    {
        $state = $request->input('state');

        $user = User::query()->where('id', $id)->first();

        if (!$user) return $this->response([],'查无此人',500);

        $user->state = $state;
        $user->save();

        return $this->response($user,'修改成功');
    }

    // 用户观看视频完毕后增加积分
    public function user_integral(Request $request)
    {
        $config = Config::query()->where('key','adIntegral')->first();
        if (!$config) return $this->response(['success' => false, 'msg' => '未配置广告参数']);
        $integral = $config->val;
        
        $user = $request->user();
        if ($user->id != $request->post('userId')) return $this->response(['success' => false, 'msg' => '用户错误']);

        // 给用户增加积分
        $user->incIntegral($integral);

        // 添加积分记录
        Record::query()->create([
            'mode'=> 1,
			'name'=> '看广告获得积分',
			'integral'=> $integral,
			'user_id'=> $user->id
        ]);

        return $this->response(['success' => true, 'integral' => $integral]);
    }

    public function count()
    {
        $count = User::query()->count();
        return $this->response(['count' => $count]);
    }

    public function user_list(Request $request)
    {
        $pageIndex = $request->get('pageIndex');
        $pageSize = $request->get('pageSize');
        $state = $request->get('state');

        $users = User::query()
            ->where('state', $state)
            ->paginate($pageSize, ['*'], 'pageIndex', $pageIndex);

        return $this->response($users);
    }
}
